package com.sc.web.order;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.dal.dto.order.OrderDetailDto;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.model.ParamMap;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.member.MemberNews;
import com.sc.dal.model.order.Express;
import com.sc.dal.model.order.Order;
import com.sc.dal.model.order.OrderPayment;
import com.sc.dal.model.order.Orders;
import com.sc.dal.model.order.Products;
import com.sc.service.goods.GoodsService;
import com.sc.service.order.OrderService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.JsonUtils;
import com.sc.util.data.POIUtils;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;
import com.sc.web.BaseController;
import com.sc.web.annotation.SystemLog;
import com.sc.web.plugin.PageView;


@Controller
@RequestMapping("/order/")
public class OrderController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Inject
	private OrderService orderService;
	
	@Autowired
	private PromotionService  promotionService;
	
	@Autowired
	private GoodsService goodsService;
	
	/**
	 * 订单列表页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return "/order/list";
	}

	/**
	 * 分页查询订单列表
	 * @param pageNow
	 * @param pageSize
	 * @param column
	 * @param sort
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage( String pageNow,
			String pageSize,String column,String sort) throws Exception {
		//查询订单数据
		ParamMap paramMap = getFormMap(ParamMap.class);
		paramMap = toFormMap(paramMap, pageNow, pageSize,paramMap.getStr("orderby"));
		if(column != null && column.equals("orderId")){
			paramMap.put("column", "order_id");	
		}else{
			paramMap.put("column", column);
		}
		if(sort != null && sort.equals("orderId")){
			paramMap.put("sort", "order_id");	
		}else{
			paramMap.put("sort", sort);
		}
        pageView.setRecords(orderService.selectList(paramMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	/**
	 * 导出订单列表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/export")
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "订单列表";
		ParamMap paramMap = findHasHMap(ParamMap.class);
		String exportData = paramMap.getStr("exportData");// 列表头的json字符串

		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);

		List<Orders> list =orderService.selectList(paramMap);
		List<ParamMap> lis = new ArrayList<ParamMap>();
		for(Orders order :list){
			ParamMap map = new ParamMap();
			map.put("orderId", order.getOrderId());
			map.put("memberName", order.getMemberName());
			map.put("itemnum", order.getItemnum());
			map.put("totalAmount", order.getTotalAmount());
			String status = order.getStatus();
			switch(status){
			   case "0": status = "普通订单";
			       break;
			   case "1": status = "已作废";
		          break;
			   case "2": status = "活动订单";
		          break;
			   case "3": status = "已完成";
		          break;
		       default : status ="普通订单";
		         break;
			}
			map.put("status", status);
			String payStatus = order.getPayStatus();
			switch(payStatus){
			   case "1":payStatus="支付成功";
			      break;
			   case "2":payStatus="支付失败";
			      break;
			   case "3":payStatus="未支付";
			      break;
			   case "4":payStatus="处理异常";
			      break;
			   case "5":payStatus="非法参数";
			      break;
			   case "6":payStatus="银行已经受理";
			      break;
			   case "7":payStatus="已付款至担保方";
			      break;
			   case "8":payStatus="超时";
			      break;
			   case "9":payStatus="准备中";
			      break;
			      default : payStatus="支付失败";
			}
			map.put("payStatus", payStatus);
			String shipStatus = order.getShipStatus();
			switch(shipStatus){
			   case "0":shipStatus="未发货";
			      break;
			   case "1":shipStatus="已发货";
			      break;
			   case "2":shipStatus="部分发货";
			      break;
			   case "3":shipStatus="部分退货";
			      break;
			   case "4":shipStatus="已退货";
			      break;
			   case "5":shipStatus="已签收";
			      break;
			   case "6":shipStatus="e贸易订单，已填写运单号，待申报";
			      break;
			}
			map.put("shipStatus", shipStatus);
			map.put("shipMethod", order.getShipMethod());
			map.put("shipMoney", order.getShipMoney());
			map.put("orderPayTime", order.getOrderPayTime());
			map.put("orderShipTime", order.getOrderShipTime());
			map.put("orderOverTime", order.getOrderOverTime());
			lis.add(map);
		}
		POIUtils.exportToExcel(response, listMap, lis, fileName);
	}
	
    //编辑订单页面
	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String orderId = getPara("id");
        Order order =orderService.selectOrderByOrderId(orderId);
        model.addAttribute("order", order);
		return "/order/edit";
	}
	 //编辑订单
	@ResponseBody
	@RequestMapping("updateOrder")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="订单管理",methods="订单列表-修改订单")//凡需要处理业务逻辑的.都需要记录操作日志
	public String updateOrder(Model model ,Order order){
		Session session = SecurityUtils.getSubject().getSession();
		Integer userId = (Integer) session.getAttribute("userSessionId");
		//0:未发货;1:已发货;2:部分发货;3:部分退货;4:已退货; 5：已签收，6：e贸易订单，已填写运单号，待申报
		MemberNews news = new MemberNews(); //交易物流消息
		try{
			order.setModifier(userId+""); //此处订单编辑人是web后台管理员
			order.setModifyDate(new Date());
			String  shipTimeStr = order.getShipTimeStr();
			String  payDeadlineStr = order.getPayDeadlineStr();
			if(Common.isNotEmpty(shipTimeStr)){
				
			}

		    	news.setCreateDate(new Date());
		    	news.setModifyDate(new Date());  
			  order.setShipTime(DateUtil.dateStrToYMDHMSDate(shipTimeStr));
			if(Common.isNotEmpty(payDeadlineStr))
			  order.setPayDeadline(DateUtil.dateStrToYMDHMSDate(payDeadlineStr));
			//修改订单状态
			int updateOrderResult = orderService.updateOrder(order);
			
			Order o = orderService.selectByPrimaryKey(order.getOrderId());
			
			OrderPayment payment = new OrderPayment();
			payment.setOrderId(order.getOrderId());
			payment = orderService.selectByPayments(payment).get(0);
			payment.setIsValid(order.getIsValid());
			payment.setMoney(order.getTotalAmount());
			payment.setMemo(order.getMemo());
			payment.setModifyDate(new Date());
			payment.setModifier(userId+"");//此处订单编辑人是web后台管理员
			
			//修改订单支付状态
			int updateOrderPaymentResult =orderService.updateOrderPayment(payment);
			if(updateOrderResult > 0 && updateOrderPaymentResult > 0){	
				String ship_status = order.getShipStatus();
		    	news.setCreater(userId+"");
		    	news.setModifier(userId +"");
				news.setOrderId(o.getOrderId());
		    	news.setMemberId(o.getCreater());
				switch(ship_status){
				    case "1":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEB);
				    	//生成一条消息通知
						orderService.insertMemberNews(news);
				    	break;
				    case  "2":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEB);
				    	//生成一条消息通知
						orderService.insertMemberNews(news);
				    	break; 
				    case  "3":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLED);
				    	//生成一条消息通知
						orderService.insertMemberNews(news);
				    	break; 
				    case  "4":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLED);
				    	//生成一条消息通知
						orderService.insertMemberNews(news);
				    	break; 
				    case  "5":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEF);
				    	//生成一条消息通知
						orderService.insertMemberNews(news);
				    	break;
				    case  "6":
						news.setNewsTitle(Constants.OrderDetail.OrderDeliver.SHIP_STATUS_TITLEG);
				    	//生成一条消息通知
				    	orderService.insertMemberNews(news);
				    	break;  

				}
				return "\"success\"";
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("修改订单数据异常:"+e);
			throw new ScBizException("修改订单数据异常！", e);
		}
		return "\"false\"";
	}
	
	/**
	 * 获取发货方式列表
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("expressList")
	public List<Express> expressList(Model model){
		try{
			List<Express> expList=  orderService.selectByParam();
			return expList;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("查询快递列表数据异常:"+e);
			throw new ScBizException("查询快递列表数据异常！", e);
			
		}
	}
	/**
	 * 删除订单
	 * @param txtGroupsSelect
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteOrder")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="订单管理",methods="订单列表-删除订单")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteOrder(String txtGroupsSelect) throws Exception{
		String idStr = getPara("ids");
		String[] ids = idStr.split(",");
		for (String orderId : ids) {
			Order o = new Order();
			o.setOrderId(orderId);
			o.setIsDelete(Constants.IS_DELETEB);
			orderService.updateOrder(o);
		}
		return "\"success\"";
	}
 	/**
	 * 发货
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/shipUI")
	public String shipUI(Model model) throws Exception {
		String orderId = getPara("id");
        Order order =orderService.selectOrderByOrderId(orderId);
        model.addAttribute("order", order);
		return "/order/ship";
	}

	//订单详情页面框架
	@RequestMapping(value="/order_details_frame")
	public String order_details_frame(Model model){
		String orderId = getPara("orderId");
		model.addAttribute("orderId", orderId);
		return "/order/order_details_frame";
	}

	//订单详情页面
	@RequestMapping(value="/order_details")
	public String order_details(){
		return "/order/order_details";
	}
	/**
	 * @Title: oneOrder
	 * @Description 根据订单ID查询订单中订单详情
	 * @date 2017年3月16日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value = "oneOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> oneOrder(String orderId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if(Common.isEmpty(orderId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
            OrderDetailDto dto = orderService.selectOrderDetailByOrderId(orderId);
            
			List<Products> list = dto.getProducts();
			if(list != null && list.size() >0){
				for(Products product:list){
					//根据会员的代理商等级查询代理等级的商品折扣率
					//product = goodsService.discoutProducts(product, dto.getMemberId());
					String imgUrl = product.getImgUrl();
					String imgUrl_new = "";
					if(Common.isNotEmpty(imgUrl)){
						String[] urls = imgUrl.split(",");
						for(String url:urls){
							imgUrl_new += ConfigBeanAdapter.fileAccessAddress + url +",";
						}
						product.setImgUrl(imgUrl_new);
					}
					product.setPicture(ConfigBeanAdapter.fileAccessAddress + product.getPicture());
					product = getProProduct(dto,product);
				}
			}
			dto = getProOrderDetail(dto); //获取订单促销活动
			resultMap.put("data", dto);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	//获取商品的促销方案
		public Products getProProduct( OrderDetailDto dto ,Products product){
			//计算商品的促销活动
			if(Common.isNotEmpty(dto.getProType()) && dto.getProType().equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_A)){ //部分商品促销
	        	String pro_goods = dto.getProGoods();
	        	String pro_detail_id = dto.getProDetailId();
	        	if(Common.isNotEmpty(pro_goods) && Common.isNotEmpty(pro_detail_id)){
	        		String[] proGoods = pro_goods.split(",");
	        		String[] proDetailIds = pro_detail_id.split(",");
	        		for(int i = 0; i< proGoods.length;i++ ){
	        			String goodsId = proGoods[i];
	        			if(Common.isNotEmpty(goodsId)){
	                        String proDetailId = proDetailIds[i];
	            			PromotionDetailDto proDetailDto =promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));
	                        Date now_time = new Date(); //现在时间
	    				    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
	    				    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
	    				    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
	    						Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
	    						//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
	    						proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
	    						proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
	    						proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
	    						String pro_type = proDetailDto.getPro_type();
	    						String pro_money = proDetailDto.getPro_money();
	    						String pro_count = proDetailDto.getPro_count();
	    						String pro_rate = proDetailDto.getPro_rate();								

	    						String pro_gooods = proDetailDto.getPro_goods();
	    						proDetailMap.put("productId", product.getProductId());
	    						proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
	    						proDetailMap.put("proType", pro_type);//促销类型
	    						proDetailMap =proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
	    						product.setGoodsProMap(proDetailMap);
	    				    }
	        			}
					
	        		}
	        	}
	        }
			return product;
		}

		//获取订单促销方案
		public OrderDetailDto getProOrderDetail( OrderDetailDto dto){
			try{
				if(Common.isNotEmpty(dto.getProType()) && dto.getProType().equals(Constants.OrdersPromotion.ORDER_SALE_PROMOTION_TYPE_B)){
		        	String pro_detail_id = dto.getProDetailId();
		        	if(Common.isNotEmpty(pro_detail_id)){
		        		String[] proDetailIds = pro_detail_id.split(",");
		        		for(String proDetailId :proDetailIds){
		        			if(Common.isEmpty(proDetailId)){
		        				continue;
		        			}
			        		PromotionDetailDto proDetailDto =promotionService.selectProDetailByPrimaryKey(Integer.valueOf(proDetailId));
		                    Date now_time = new Date(); //现在时间
						    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
						    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
						    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
								Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
								//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
								proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
								proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
								proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
								String pro_type = proDetailDto.getPro_type();
								String pro_money = proDetailDto.getPro_money();
								String pro_count = proDetailDto.getPro_count();
								String pro_rate = proDetailDto.getPro_rate();	
								String pro_gooods = proDetailDto.getPro_goods();
								proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
								proDetailMap.put("proType", pro_type);//促销类型
								proDetailMap =proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
								dto.setProDetailMap(proDetailMap);
						    }
		        		}
	    			}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
			return dto;
		}
		/**
		 * 封装促销活动返回集合
		 * @param proDetailMap
		 * @param pro_type
		 * @param pro_money
		 * @param pro_count
		 * @param pro_rate
		 * @param pro_gooods
		 * @return
		 */
		public Map<String ,Object> proDetailMap(Map<String ,Object> proDetailMap,String pro_type,String pro_money,String pro_count,String pro_rate,String pro_gooods){
			 List<Goods> goodsList =new ArrayList<Goods>();//满赠商品列表  
				String[] goods_ids =null;
				if(Common.isNotEmpty(pro_gooods)){
					goods_ids =pro_gooods.split(",");
					for(String goods_id : goods_ids){
						Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(goods_id));
						goodsList.add(goods);
					}
				}
			switch(pro_type){
				case "0": //订单满减
					if(Common.isNotEmpty(pro_money)){
						proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
						proDetailMap.put("discountAmount", pro_money.split(":")[1]);
					}
					break;
				case "1": //商品满减
					if(Common.isNotEmpty(pro_money)){
						proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
						proDetailMap.put("discountAmount", pro_money.split(":")[1]);
					}
					break;
				case "2": //商品满赠
					if(Common.isNotEmpty(pro_count)){
						proDetailMap.put("mustQuantity", pro_count.split(":")[0]);
						proDetailMap.put("giveNumber", pro_count.split(":")[1]);
						proDetailMap.put("giveList", goodsList);
					}
					break;
				case "3":  //商品打折
					if(Common.isNotEmpty(pro_count)){
						proDetailMap.put("mustQuantity", pro_count);//商品满足数量
						BigDecimal rate = new BigDecimal(new Double(pro_rate)/100).setScale(2, BigDecimal.ROUND_HALF_UP);
						proDetailMap.put("discountRate",rate.toString());//商品打折率
					}
					break;
			}
			return proDetailMap;
		}

}
